import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:zentoon_flutter/screens/mine/coin_history_screen.dart';
import 'package:zentoon_flutter/screens/mine/model/gems_model.dart';

import '../../models/comic_user_model.dart';
import '../../providers/comic_provider.dart';
import '../../utils/appsflyer_event_manager.dart';
import '../../utils/http_helper.dart';
import '../../utils/user_manager.dart';

class TopUpScreen extends StatefulWidget {
  const TopUpScreen({super.key});

  @override
  State<TopUpScreen> createState() => _TopUpScreenState();
}

class _TopUpScreenState extends State<TopUpScreen> {
  int selectedCoinPackage = -1;
  int currentCoins = 0;

  bool _purchasePending = false;

  // Add purchase manager instance
  List<GemsModel> _purchasePackages = [];

  // IAP相关变量
  final FlutterInappPurchase _iap = FlutterInappPurchase.instance;
  bool _connected = false;
  bool _loading = false;
  StreamSubscription<Purchase>? _purchaseUpdatedSubscription;
  StreamSubscription<PurchaseError>? _purchaseErrorSubscription;
  final Set<String> _processedTransactionIds = {};
  final Set<String> _processedErrorMessages = {};

  // Color variables
  final Color primaryAccent = const Color(0xFF724CF9);
  final Color secondaryAccent = const Color(0xFFF9C84C);
  final Color textPrimary = Colors.white;
  final Color textSecondary = Colors.white70;
  final Color borderColor = const Color(0xFF3D2F4F);
  final Color successColor = const Color(0xFF4ECDC4);
  final Color shadowColor = Colors.black.withOpacity(0.3);

  @override
  void initState() {
    super.initState();
    _initConnection();
    Future.microtask(() => _fetchData());
  }

  @override
  void dispose() {
    _purchaseUpdatedSubscription?.cancel();
    _purchaseErrorSubscription?.cancel();
    _iap.endConnection();
    super.dispose();
  }

  /// 初始化IAP连接
  Future<void> _initConnection() async {
    if (!mounted) return;
    setState(() {
      _loading = true;
    });

    try {
      await _iap.initConnection();
      if (!mounted) return;
      setState(() {
        _connected = true;
      });

      _setupPurchaseListeners();
      await _loadProducts();
    } catch (e) {
      debugPrint('Failed to initialize IAP connection: $e');
      if (mounted) {
        setState(() {});
      }
    } finally {
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  /// 设置购买监听器
  void _setupPurchaseListeners() {
    debugPrint('Setting up purchase listeners...');

    // 监听购买更新
    _purchaseUpdatedSubscription = _iap.purchaseUpdatedListener.listen(
      (purchase) {
        debugPrint('🎉 Purchase update received!');
        debugPrint('ProductId: ${purchase.productId}');
        debugPrint('TransactionId: ${purchase.transactionIdFor}');
        _handlePurchaseUpdate(purchase);
      },
      onError: (Object error) {
        debugPrint('❌ Purchase stream error: $error');
      },
    );

    // 监听购买错误
    _purchaseErrorSubscription = _iap.purchaseErrorListener.listen(
      (purchaseError) {
        debugPrint('❌ Purchase error received!');
        debugPrint('Error code: ${purchaseError.code}');
        debugPrint('Error message: ${purchaseError.message}');

        // 防止重复处理错误
        final errorKey = purchaseError.message;
        if (_processedErrorMessages.contains(errorKey)) {
          debugPrint('ℹ️ Error already processed: $errorKey');
          return;
        }
        _processedErrorMessages.add(errorKey);

        _handlePurchaseError(purchaseError);
      },
      onError: (Object error) {
        debugPrint('❌ Error stream error: $error');
      },
    );

    debugPrint('Purchase listeners setup complete');
  }

  /// 加载产品信息
  Future<void> _loadProducts() async {
    setState(() {});
    try {
      final response = await HttpUtil().getModel<List<GemsModel>>(
        'ComicMember/GetRechargePriceLists',
        fromJson: (json) =>
            (json as List).map((item) => GemsModel.fromJson(item)).toList(),
      );
      if (response?.status == 200 && response?.result != null) {
        if (!mounted) return;
        setState(() {
          _purchasePackages = response?.result ?? [];
        });
      } else {
        if (!mounted) return;
        setState(() {
          _purchasePackages = [];
        });
      }
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _purchasePackages = [];
      });
    }
  }

  /// 处理购买更新
  Future<void> _handlePurchaseUpdate(Purchase purchase) async {
    debugPrint('🎯 Purchase update received: ${purchase.productId}');

    if (!mounted) return;

    final transactionId = purchase.transactionIdFor;

    // 检查是否已处理过此交易
    if (transactionId != null &&
        _processedTransactionIds.contains(transactionId)) {
      debugPrint('⚠️ Transaction already processed: $transactionId');
      return;
    }

    // 判断购买是否成功
    bool isPurchased = false;

    if (purchase is PurchaseIOS) {
      final bool condition1 =
          purchase.iosTransactionState == TransactionState.purchased;
      final bool condition2 =
          purchase.purchaseToken != null && purchase.purchaseToken!.isNotEmpty;
      final bool condition3 = transactionId != null;

      isPurchased = condition1 || condition2 || condition3;
    }

    if (!isPurchased) {
      debugPrint('❓ Purchase not detected as successful');
      if (mounted) {
        setState(() {
          _purchasePending = false;
        });
        // 注释掉这行，避免第三个错误提示
        // _showErrorSnack('Purchase state unknown');
      }
      return;
    }

    debugPrint('✅ Purchase detected as successful: ${purchase.productId}');

    // 标记交易已处理
    if (transactionId != null) {
      _processedTransactionIds.add(transactionId);
    }

    // 验证购买
    await _verifyPurchase(purchase);

    // 完成交易
    try {
      await _iap.finishTransaction(purchase, isConsumable: true);
      debugPrint('Transaction finished successfully');
    } catch (e) {
      debugPrint('Error finishing transaction: $e');
    }
  }

  /// 处理购买错误
  void _handlePurchaseError(PurchaseError error) {
    if (!mounted) return;

    setState(() {
      _purchasePending = false;
    });

    // 检查是否为用户取消
    final errorString = error.toString().toLowerCase();
    final bool isUserCancelled = (error.code == ErrorCode.UserCancelled) ||
        errorString.contains('user_cancel') ||
        errorString.contains('user cancelled') ||
        errorString.contains('canceled') ||
        errorString.contains('cancelled');

    if (isUserCancelled) {
      debugPrint('ℹ️ Purchase cancelled by user');
      EasyLoading.showToast("Purchase cancelled");
      return;
    }

    // 避免重复显示错误（如果已经在_processPayment中显示过）
    debugPrint('❌ Purchase error from listener: ${error.message}');
    // 注释掉这行，避免重复错误提示
    // _showErrorSnack('Purchase failed: ${error.message}');
    EasyLoading.showError('Purchase failed: ${error.message}');
  }

  /// 处理支付流程
  Future<void> _processPayment() async {
    if (selectedCoinPackage < 0) {
      _showErrorSnack('Please select a package');
      return;
    }

    if (!_connected) {
      _showErrorSnack('Store connection not available');
      return;
    }

    if (_purchasePackages.isEmpty) {
      _showErrorSnack('No packages available');
      return;
    }

    final selectedPackage = _purchasePackages[selectedCoinPackage];
    // 修复：直接使用硬编码的产品ID，移除无用的null检查
    // String productId = "app_meiyou_chong80";
    String productId = selectedPackage.code ?? "";

    debugPrint('🛒 Starting purchase for: $productId');

    if (!mounted) return;
    setState(() {
      _purchasePending = true;
      _processedErrorMessages.clear(); // 清除之前的错误记录
    });

    try {
      // 构建购买请求
      final requestProps = RequestPurchaseProps.inApp(
        request: RequestPurchasePropsByPlatforms(
          ios: RequestPurchaseIosProps(sku: productId, quantity: 1),
          android: RequestPurchaseAndroidProps(skus: [productId]),
        ),
      );

      await _iap.requestPurchase(requestProps);
      debugPrint('✅ Purchase request sent successfully');

      // 购买结果将通过监听器处理
    } catch (error) {
      if (mounted) {
        setState(() {
          _purchasePending = false;
        });
      }

      // 检查是否为用户取消
      final errorString = error.toString().toLowerCase();
      final bool isUserCancelled = errorString.contains('user_cancel') ||
          errorString.contains('user cancelled') ||
          errorString.contains('canceled') ||
          errorString.contains('cancelled');

      if (isUserCancelled) {
        debugPrint('ℹ️ Purchase cancelled by user');
        EasyLoading.showToast("Purchase cancelled");
        return;
      }

      // 只在这里显示一次错误，避免重复
      // debugPrint('❌ Purchase request failed: $error');
      // EasyLoading.showToast("Purchase request failed: $error");
    }
  }

  /// Verify purchase receipt + distribute coins
  Future<void> _verifyPurchase(Purchase purchase) async {
    EasyLoading.show(status: "Verifying order...");
    try {
      final response = await HttpUtil().postJson(
        'ComicMember/ValidApple',
        data: {
          "validId": purchase.productId,
          "transactionId": purchase.transactionIdFor,
          "appleReceipt": purchase.purchaseToken,
          "isSanDbox": false,
          "type": 1,
        },
      );

      if (mounted) {
        EasyLoading.dismiss();
        setState(() {
          _purchasePending = false;
        });

        if (response?["status"] == 200) {
          EasyLoading.showToast("Recharge successful");
          await _fetchData(); // Refresh balance after success
          await AppsFlyerEventManager.logFristTouup();
        } else {
          _showErrorSnack("Server error: ${response?["message"]}");
        }
      }
    } catch (e) {
      if (mounted) {
        EasyLoading.dismiss();
        setState(() {
          _purchasePending = false;
        });
        _showErrorSnack("Verification exception: $e");
      }
    }
  }

  /// Get recharge list
  Future<void> _fetchData() async {
    // Get user info and update coin balance
    UserData? userInfo;
    try {
      userInfo = await UserManager.getUserInfo();
    } catch (e) {
      // Failed to get user info, continue execution
      print('Failed to get user info: $e');
    }

    setState(() {
      currentCoins =
          userInfo?.balance?.toInt() ?? 0; // Get real balance from user info
    });
  }

  /// Error notification
  void _showErrorSnack(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(msg),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF211839),
      appBar: AppBar(
        backgroundColor: const Color(0xFF211839),
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: textPrimary),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          'Top-Up',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: Icon(Icons.history, color: textPrimary),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const CoinHistoryScreen(),
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 12),

            // Premium会员卡片
            _buildPremiumCard(),

            const SizedBox(height: 30),

            // 充值套餐列表
            if (_loading)
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 40),
                child: CircularProgressIndicator(color: Color(0xFF7B68EE)),
              )
            else if (_purchasePackages.isEmpty)
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 40),
                child: Text(
                  'No recharge packages available',
                  style: TextStyle(color: Colors.white54, fontSize: 16),
                ),
              )
            else
              ..._purchasePackages.asMap().entries.map((entry) {
                final index = entry.key;
                final package = entry.value;
                return _buildCoinPackage(package, index);
              }),

            const SizedBox(height: 20),

            // 底部金币信息和充值按钮
            _buildBottomActionBar(),

            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  // 构建Premium会员卡片
  Widget _buildPremiumCard() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [primaryAccent, const Color(0xFF764BA2)],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            blurRadius: 15,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
            decoration: BoxDecoration(
              color: textPrimary.withOpacity(0.9),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              'JOIN PREMIUM',
              style: TextStyle(
                color: successColor,
                fontSize: 12,
                fontWeight: FontWeight.w600,
                letterSpacing: 0.5,
              ),
            ),
          ),
          const SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildPremiumFeature(
                icon: Icons.auto_stories,
                iconColor: const Color(0xFF6C63FF),
                title: 'Premium free\ncomic',
              ),
              Container(
                width: 1,
                height: 40,
                color: textPrimary.withOpacity(0.3),
              ),
              _buildPremiumFeature(
                icon: Icons.block,
                iconColor: const Color(0xFFFF6B6B),
                title: 'Remove Ads',
              ),
              Container(
                width: 1,
                height: 40,
                color: textPrimary.withOpacity(0.3),
              ),
              _buildPremiumFeature(
                icon: Icons.schedule,
                iconColor: const Color(0xFF9C88FF),
                title: 'Read in advance',
              ),
            ],
          ),
          const SizedBox(height: 24),
          GestureDetector(
            onTap: () => _navigateToPremium(),
            child: Container(
              alignment: Alignment.center,
              width: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [secondaryAccent, const Color(0xFFD69E2E)],
                ),
                borderRadius: BorderRadius.circular(20),
                boxShadow: [
                  BoxShadow(
                    color: secondaryAccent.withOpacity(0.4),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: const Text(
                'Go Premium',
                style: TextStyle(
                  color: Color(0xFF1A202C),
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建Premium功能项
  Widget _buildPremiumFeature({
    required IconData icon,
    required Color iconColor,
    required String title,
  }) {
    return Column(
      children: [
        Container(
          width: 40,
          height: 40,
          decoration: BoxDecoration(
            color: textPrimary,
            borderRadius: BorderRadius.circular(20),
            boxShadow: [
              BoxShadow(
                color: shadowColor.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Icon(icon, color: iconColor, size: 20),
        ),
        const SizedBox(height: 8),
        Text(
          title,
          textAlign: TextAlign.center,
          style: TextStyle(
            color: textPrimary,
            fontSize: 10,
            fontWeight: FontWeight.w500,
            height: 1.2,
          ),
        ),
      ],
    );
  }

  // 构建错误提示视图
  Widget _buildErrorView(String errorMessage) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 40, horizontal: 20),
      child: Column(
        children: [
          Text(
            errorMessage,
            style: TextStyle(color: textPrimary, fontSize: 16),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: () => {},
            style: ElevatedButton.styleFrom(
              backgroundColor: primaryAccent,
              foregroundColor: textPrimary,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
            ),
            child: const Text('Try Again'),
          ),
        ],
      ),
    );
  }

  // 构建金币套餐卡片
  Widget _buildCoinPackage(GemsModel package, int index) {
    final isSelected = selectedCoinPackage == index;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
      child: Stack(
        children: [
          GestureDetector(
            onTap: () => setState(() => selectedCoinPackage = index),
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: isSelected
                    ? successColor.withOpacity(0.2)
                    : const Color(0xFF2A1F3D),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected ? Color(0xFF7B68EE) : borderColor,
                  width: isSelected ? 2 : 1,
                ),
                boxShadow: [
                  BoxShadow(
                    color: shadowColor,
                    blurRadius: 12,
                    offset: const Offset(0, 6),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: primaryAccent.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Icon(Icons.diamond, color: primaryAccent, size: 24),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '${package.num} Coins',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Color(0xFF7B68EE),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Text(
                    '\$${package.amount?.toStringAsFixed(2)}',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF7B68EE),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建底部操作栏
  Widget _buildBottomActionBar() {
    return Container(
      margin: const EdgeInsets.all(20),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF2A1F3D),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: const Color(0xFF7B68EE), width: 1),
        boxShadow: [
          BoxShadow(
            color: shadowColor,
            blurRadius: 15,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: primaryAccent.withOpacity(0.2),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(Icons.diamond, color: primaryAccent, size: 24),
          ),
          const SizedBox(width: 12),
          Text(
            '$currentCoins',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: textPrimary,
            ),
          ),
          const Spacer(),
          ElevatedButton(
            onPressed:
                (selectedCoinPackage >= 0 && _connected && !_purchasePending)
                    ? _processPayment
                    : null,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFF7B68EE),
              foregroundColor: textPrimary,
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              elevation: 0,
            ),
            child: _purchasePending
                ? const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                : const Text(
                    'Recharge',
                    style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
                  ),
          ),
        ],
      ),
    );
  }

  // 导航到Premium页面
  void _navigateToPremium() {
    Navigator.of(context).pop();
    if (context.mounted) {
      final container = ProviderScope.containerOf(context);
      container.read(bottomNavIndexProvider.notifier).state = 2;
    }
  }
}
